package com.lsz.intelligentflowerwatering

import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Intent
import android.content.IntentFilter
import android.location.LocationManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Scaffold
import androidx.lifecycle.lifecycleScope
import com.espressif.provisioning.ESPProvisionManager
import com.google.accompanist.navigation.animation.rememberAnimatedNavController
import com.lsz.intelligentflowerwatering.ui.MyAppNavHost
import com.lsz.intelligentflowerwatering.ui.MyTopAppBar
import com.lsz.intelligentflowerwatering.ui.theme.MyComposeTheme
import com.lsz.intelligentflowerwatering.viewmodel.MainViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import com.lsz.intelligentflowerwatering.ui.dialog
import com.lsz.intelligentflowerwatering.ui.toast
import com.lsz.intelligentflowerwatering.viewmodel.BleState
import com.lsz.intelligentflowerwatering.viewmodel.BleViewModel

@OptIn(ExperimentalAnimationApi::class)
class MainActivity : ComponentActivity(), ActivityResultCallback<Map<String, Boolean>> {

    private val mainViewModel by viewModels<MainViewModel>()
    private val bleViewModel by viewModels<BleViewModel>()

    private val tag = "the process"
    private lateinit var broadcastReceiver: BroadcastReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        ESPProvisionManager.getInstance(this)
        broadcastReceiver = MainBroadcastReceiver(mainViewModel, bleViewModel)

        /**
         * 根据版本检查权限授予情况
         */
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
            PermissionIdentify.androidLowerTo12PermissionIdentify {
                val requestPermissionsLauncher =
                    registerForActivityResult<Array<String>, Map<String, Boolean>>(
                        ActivityResultContracts.RequestMultiplePermissions(), this
                    )
                requestPermissionsLauncher.launch(it)
                Log.i(tag, "android<12")
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PermissionIdentify.androidHigherTo12PermissionIdentify {
                val requestPermissionsLauncher = registerForActivityResult(
                    ActivityResultContracts.RequestMultiplePermissions(), this
                )
                requestPermissionsLauncher.launch(it)
                Log.i(tag, "android>=12")
            }
        }

        /**
         * 检查蓝牙和定位是否开启
         */
        lifecycleScope.launch() {
            mainViewModel.permissionState.collect {
                //当权限授权状态为true时，检查蓝牙、定位状态
                if (it) {
                    toast(context = this@MainActivity, text = "蓝牙或定位已授权")
                    val bluetoothAdapter: BluetoothAdapter = bleViewModel.bluetoothManager.adapter
                    val locationManager = bleViewModel.locationManager
                    Log.i(tag, mainViewModel.permissionState.value.toString())
                    //判断蓝牙
                    if (bluetoothAdapter.isEnabled) {
                        Log.i(tag, "bluetooth opened")
                    } else {
                        Log.i(tag, "bluetooth need been opened")
                        dialog(this@MainActivity,
                            "添加设备需要打开蓝牙，是否跳转到蓝牙设置界面？",
                            "是",
                            { _, _ -> startActivity(Intent(Settings.ACTION_BLUETOOTH_SETTINGS)) },
                            "否",
                            { _, _ ->
                                toast(this@MainActivity, text = "蓝牙未打开，无法扫描")
                            })
                    }
                    //判断定位
                    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        Log.i(tag, "location opened")
                    } else {
                        Log.i(tag, "location need been opened")
                        dialog(this@MainActivity,
                            "添加设备需要打开定位，是否跳转到定位设置界面？",
                            "是",
                            { _, _ -> startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) },
                            "否",
                            { _, _ ->
                                toast(this@MainActivity, text = "定位未打开，无法扫描")
                            })
                    }
                } else {
                    toast(context = this@MainActivity, text = "蓝牙或定位未授权")
                }
            }
        }

        setContent {
            Log.i("the process", "UI")
            MyComposeTheme(MyComposeTheme.Theme.Light) {
                val navController = rememberAnimatedNavController()
                Column() {
                    MyTopAppBar(title = mainViewModel.navTitles[mainViewModel.count],
                        count = mainViewModel.count,
                        back = {
                            navController.navigateUp()
                            toLeft()
                        })
                    MyAppNavHost(lifecycleScope = lifecycleScope,
                        bleViewModel = bleViewModel,pageChange = {
                        if (it) toRight() else toLeft()
                    }, jumpToFront = {
                        val uri: Uri = Uri.parse("http://192.168.1.137:5500/manage.html")
                        val intent = Intent(Intent.ACTION_VIEW, uri)
//                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK    //开启新的Task
                        startActivity(intent)
                        //把该activity销毁
                        finish()
                    })
                }
                BackHandler() {
                    navController.navigateUp()
                    toLeft()
                }
            }
        }

        //注册广播接收器
        val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
        filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION)
        registerReceiver(broadcastReceiver, filter)
    }

    override fun onActivityResult(result: Map<String, Boolean>?) {
        if (result != null) {
            Log.i(tag, "permitted")
            for ((_, granted) in result) {
                if (granted) {
                    mainViewModel.permissionState.value = true
                } else {
                    mainViewModel.permissionState.value = false
                    //有未授权的立即结束
                    return
                }
            }
        }
    }

    private fun toRight() {
        lifecycleScope.launch {
            println(Thread.currentThread().name)
            delay(500L)
            if (mainViewModel.count < 2) mainViewModel.count++
        }
    }

    private fun toLeft() {
        lifecycleScope.launch {
            println(Thread.currentThread().name)
            delay(500L)
            if (mainViewModel.count > 0) mainViewModel.count--
        }
    }

    override fun onResume() {
        super.onResume()
        bleViewModel.bleScanStart()

//        bleViewModel.bleState = BleState.ScanBegin

    }
}